package com.sense.kukoo.biz_media.view

import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.share.Sharer
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.widget.ShareDialog
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.gyf.immersionbar.ImmersionBar
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_media.R
import com.sense.kukoo.biz_media.databinding.BizMediaActivityMediaDescriptionBinding
import com.sense.kukoo.biz_media.vm.MediaDescriptionViewModel
import com.sense.kukoo.common.anim.BottomMotionAnimHelper
import com.sense.kukoo.common.anim.UpOrDownAnimHelper
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.constant.ConstantConfig
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.http.bean.ContentInfoBean
import com.sense.kukoo.common.utils.*
import com.sense.kukoo.common.wiget.adapter.CommonPagerAdapter
import com.sense.kukoo.common.wiget.dialog.AddCommentDialog
import com.sense.kukoo.common.wiget.dialog.BottomLoginDialog
import com.sense.kukoo.common.wiget.dialog.MediaSettingDialog
import com.sense.kukoo.common.wiget.dialog.MediaShareDialog
import com.sense.kukoo.common.wiget.state.NetworkErrorState
import com.sense.kukoo.lib_logger.LoggerManager
import com.sense.kukoo.lib_picture.config.GlideConfig
import com.sense.kukoo.lib_picture.loader.Monet
import com.zy.multistatepage.MultiStateContainer
import com.zy.multistatepage.bindMultiState
import com.zy.multistatepage.state.SuccessState

@Route(path = ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_DESCRIPTION_ACTIVITY)
class MediaDescriptionActivity : BaseMvvmActivity<MediaDescriptionViewModel, BizMediaActivityMediaDescriptionBinding>() {

    private val TAG: String = javaClass.simpleName

    private lateinit var tab_description: Array<String>
    private lateinit var mAdapter: CommonPagerAdapter

    private var mFragments:ArrayList<Fragment> = arrayListOf<Fragment>()
    private var isSeekBarTracking = false
    private var mMultiState: MultiStateContainer? = null
    private var callbackManager : CallbackManager? = null

    private var mBottomLoginDialog: BottomLoginDialog? = null
    private var mMediaSettingDialog: MediaSettingDialog? = null
    private var mAddCommentDialog: AddCommentDialog? = null
    private var mMediaShareDialog: MediaShareDialog? = null

    private lateinit var mSimpleDescriptionFragment: SimpleDescriptionFragment
    private lateinit var mMediaCommentFragment: MediaCommentFragment
    private val mAnimHelper = BottomMotionAnimHelper()
    private val mBtnListenAnimHelper = UpOrDownAnimHelper()
    private val mMusicPlayerAnimHelper = UpOrDownAnimHelper()

    @JvmField
    @Autowired(name = ARouterUrl.KEY_FROM)
    var from: String? = null

    override fun getLayoutId(): Int = R.layout.biz_media_activity_media_description

    override fun getViewModelClass(): Class<MediaDescriptionViewModel> = MediaDescriptionViewModel::class.java

    override fun responseVM(action: Int) {}

    override fun initStatusBar() {
        ImmersionBar.with(this)
            .transparentStatusBar()
            .navigationBarColor(com.sense.kukoo.common_design.R.color.bg_background)
            .statusBarDarkFont(true)
            .navigationBarDarkIcon(true)
            .fitsSystemWindows(false)
            .init()
    }

    override fun initData() {
        //
        ARouter.getInstance().inject(this)
        mViewModel.setFromData(from!!.toLong())
        //
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        bindAction(mViewModel.action_networkError){
            if (mMultiState == null) {
                mMultiState = mBinding.clDescriptionContent.bindMultiState()
            }
            mMultiState!!.show<NetworkErrorState> {
                it.onRetry {
                    mViewModel.getContentInfo()
                }
            }
        }
        bindAction(mViewModel.action_finish){
            mAnimHelper.animateToFinish()
        }
        bindAction(mViewModel.action_toChannel){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CHANNEL_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, it)
                .navigation()
        }
        bindAction(mViewModel.action_showLoginDialog){
            mBottomLoginDialog = BottomLoginDialog.autoShow(this)
        }
        bindAction(mViewModel.action_showShareDialog){
            showShareDialog()
        }
        bindAction(mViewModel.action_showSettingDialog){
            mMediaSettingDialog = MediaSettingDialog(this)
            mMediaSettingDialog!!.show()
        }
        bindAction(mViewModel.action_toPlayList){
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_ACTIVITY)
                .navigation()
        }
        bindAction(mViewModel.action_showAddCommentDialog){
            mAddCommentDialog = AddCommentDialog(this)
            mAddCommentDialog!!.autoShow(null) {
                mViewModel.onAddComment(it)
            }
        }
        bindAction(mViewModel.action_newComment){
            if(mBinding.viewPager.currentItem == 1){
                mMediaCommentFragment.setNewComment(it)
            }
        }
        bindAction(mViewModel.action_newMusic){
            //切换新音乐，清除dialog
            mBottomLoginDialog?.dismiss()
            mMediaSettingDialog?.dismiss()
            mAddCommentDialog?.dismiss()
            mMediaShareDialog?.dismiss()
        }
        bindData(mViewModel.data_contentInfo){
            mMultiState?.show<SuccessState>()
            setContentInfo(it)
        }
        bindData(mViewModel.data_isShowMusicPlayer){
            if(it){
                mMusicPlayerAnimHelper.animateToShow()
                mBtnListenAnimHelper.animateToHide()
            } else {
                mMusicPlayerAnimHelper.animateToHide()
                mBtnListenAnimHelper.animateToShow()
            }
        }
        bindData(mViewModel.data_isPlayerBtnPause){
            if (it) {
                //播放中
                mBinding.ivBtnMediaPlay.setImageResource(com.sense.kukoo.common_design.R.drawable.design_icon_media_pause_56dp)
            } else {
                //暂停中
                mBinding.ivBtnMediaPlay.setImageResource(com.sense.kukoo.common_design.R.drawable.design_icon_media_play_56dp)
            }
        }
        bindData(mViewModel.data_playerSeekBar){
            if (!isSeekBarTracking){
                mBinding.seekBar.max = it.max
                mBinding.seekBar.progress = it.progress
            }
        }
        bindData(mViewModel.data_btnFollowState){
            when (it) {
                MediaDescriptionViewModel.STATE_FOLLOW_GONE -> {
                    mBinding.tvBtnFollow.visibility = View.GONE
                }
                MediaDescriptionViewModel.STATE_FOLLOW_OFF -> {
                    mBinding.tvBtnFollow.visibility = View.VISIBLE
                    mBinding.tvBtnFollow.text = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.follow)
                    mBinding.tvBtnFollow.setTextColor(mBinding.tvBtnFollow.resources.getColor(com.sense.kukoo.common_design.R.color.text_white))
                    mBinding.tvBtnFollow.setBackgroundResource(com.sense.kukoo.common_design.R.drawable.design_bg_btn_follow_def)
                }
                MediaDescriptionViewModel.STATE_FOLLOW_ON -> {
                    mBinding.tvBtnFollow.visibility = View.VISIBLE
                    mBinding.tvBtnFollow.text = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.following)
                    mBinding.tvBtnFollow.setTextColor(mBinding.tvBtnFollow.resources.getColor(com.sense.kukoo.common_design.R.color.text_active))
                    mBinding.tvBtnFollow.setBackgroundResource(com.sense.kukoo.common_design.R.drawable.design_bg_btn_follow_active)
                }
            }
        }
        bindData(mViewModel.data_contentListening){
            if(it.listeningList.isEmpty()){
                mBinding.tvTitleKeep.maxLines = 2
                mBinding.recentlyListeningItem.visibility = View.GONE
                mBinding.recentlyListeningItemKeep.visibility = View.GONE
            } else {
                mBinding.tvTitleKeep.maxLines = 1
                mBinding.recentlyListeningItem.setNumber("${it.listeningNum}")
                mBinding.recentlyListeningItemKeep.setNumber("${it.listeningNum}")
                mBinding.recentlyListeningItem.setIconUrls(it.listeningList)
                mBinding.recentlyListeningItemKeep.setIconUrls(it.listeningList)
            }
        }
        bindData(mViewModel.data_btnLikeState){
            if (it) {
                mBinding.ivIconLike.setImageResource(com.sense.kukoo.common_design.R.drawable.design_icon_media_heart_fill_24dp)
            } else {
                mBinding.ivIconLike.setImageResource(com.sense.kukoo.common_design.R.drawable.design_icon_media_heart_24dp)
            }
        }
        bindData(mViewModel.data_btnLikeNumber){
            mBinding.tvLikesItem.text = "${it}"
            mBinding.tvNumberLike.text = "${it}"
        }
        bindData(mViewModel.data_btnCommentNumber){
            mBinding.tvCommentItem.text = "${it}"
            mBinding.tvNumberComment.text = "${it}"
        }
        bindData(mViewModel.data_btnShareNumber){
            mBinding.tvNumberShare.text = "${it}"
            mBinding.tvNumberShareKeep.text = "${it}"
        }
    }

    override fun initView() {
        //seekBar
        mBinding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            var userProgress = 0

            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    userProgress = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isSeekBarTracking = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isSeekBarTracking = false
                Kukoo.input.seekTo(userProgress)
            }
        })
        mBinding.seekBar.setOnClickListener {
            //seekBar的BUG，需要空白的点击事件
            LoggerManager.v(TAG, "mBinding.seekBar.setOnClick")
        }

        //appBar
        mBinding.appBarLayout.addOnOffsetChangedListener(object :AppBarLayout.OnOffsetChangedListener{

            val h1 = ApplicationContext.dp2px(16F)
            val h2 = ApplicationContext.dp2px(30F)
            val h3 = ApplicationContext.dp2px(40F)
            val h4 = ApplicationContext.dp2px(100F)

            override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
                val height = -verticalOffset
                if(height > h1){
                    mBinding.ivBtnBack.visibility = View.INVISIBLE
                } else {
                    mBinding.ivBtnBack.visibility = View.VISIBLE
                }
                if(height < h2){
                    mBinding.keep.alpha = 0F
                    mBinding.keep.translationY = -1F * h4
                } else if(height > h3){
                    mBinding.keep.alpha = 1F
                    mBinding.keep.translationY = 0F
                } else {
                    val alpha = 0.5F + 0.5F * (height - h2) / (h3 - h2)
                    mBinding.keep.alpha = alpha
                    mBinding.keep.translationY = 0F
                }
                if(height > h3){
                    mBinding.tvBtnFollow.visibility = View.INVISIBLE
                    mBinding.ivIconChannel.visibility = View.INVISIBLE
                    mBinding.ivIconChannelFg.visibility = View.INVISIBLE
                    mBinding.tvNameChannel.visibility = View.INVISIBLE
                    mBinding.ivNameChannelTag.visibility = View.INVISIBLE
                    mBinding.tvTimeAgo.visibility = View.INVISIBLE
                } else {
                    mBinding.tvBtnFollow.visibility = View.VISIBLE
                    mBinding.ivIconChannel.visibility = View.VISIBLE
                    mBinding.ivIconChannelFg.visibility = View.VISIBLE
                    mBinding.tvNameChannel.visibility = View.VISIBLE
                    mBinding.ivNameChannelTag.visibility = View.VISIBLE
                    mBinding.tvTimeAgo.visibility = View.VISIBLE
                }
                if(height > h4){
                    mBinding.tvTitleItem.visibility = View.INVISIBLE
                } else {
                    mBinding.tvTitleItem.visibility = View.VISIBLE
                }
            }
        })

        //tab
        mSimpleDescriptionFragment = SimpleDescriptionFragment.newInstance()
        mMediaCommentFragment = MediaCommentFragment.newInstance()
        mFragments.clear()
        mFragments.add(mSimpleDescriptionFragment)
        mFragments.add(mMediaCommentFragment)
        mAdapter = CommonPagerAdapter(this, mFragments)
        mBinding.viewPager.adapter = mAdapter
        mBinding.viewPager.isUserInputEnabled = true
        //
        tab_description = resources.getStringArray(com.sense.kukoo.common_i18n.R.array.array_tab_description)
        mBinding.tabDesOrComment.init(tab_description)
        TabLayoutMediator(mBinding.tabDesOrComment, mBinding.viewPager) { tab, position ->
            mBinding.tabDesOrComment.setTab(tab, position)
        }.attach()
        mBinding.tabDesOrComment.resizeItem()
        //
        mBinding.tabDesOrComment.setOnTabListener {
            mViewModel.setTabPosition(it)
        }

        //弹出动画
        val first = ApplicationContext.dp2px(800F).toFloat()
        mAnimHelper.init(mBinding.flRoot, mBinding.clDescriptionRoot, first){ finish() }
        mAnimHelper.animateToStart()
        //
        mBtnListenAnimHelper.setView(mBinding.tvBtnListenNow)
        mBtnListenAnimHelper.setAnimateDuration(200L)
        mBtnListenAnimHelper.setMaxTranslationY(mBinding.tvBtnListenNow.translationY)
        mMusicPlayerAnimHelper.setView(mBinding.containerMusicPlayer)
        mMusicPlayerAnimHelper.setAnimateDuration(200L)
        mMusicPlayerAnimHelper.setMaxTranslationY(mBinding.containerMusicPlayer.translationY)
        mMusicPlayerAnimHelper.setShowAction {
            mBinding.spaceMusicPlayer.visibility = View.VISIBLE
        }
        mMusicPlayerAnimHelper.setHideAction {
            mBinding.spaceMusicPlayer.visibility = View.GONE
        }

        //
        mViewModel.initData()
    }

    override fun onBackPressed() {
        mAnimHelper.animateToFinish()
    }

    fun setContentInfo(info: ContentInfoBean){
        Monet.get(this)
            .load<GlideConfig>(info.avatarUrl)
            .placeholder(com.sense.kukoo.common_design.R.drawable.design_icon_avatar_default)
            .circleCrop()
            .into(mBinding.ivIconChannel)
        //
        Monet.get(this)
            .load<GlideConfig>(info.coverUrl)
            .centerCropWithConner(ApplicationContext.dp2px(10F))
            .into(mBinding.ivIconMusic)
        //
        mBinding.tvNameChannel.text = info.channelName
        mBinding.tvTitleItem.text = info.title
        mBinding.tvTitleKeep.text = info.title
        //
        var min = (info.duration ?: 0) / 60
        min = if(min == 0) 1 else min
        val hour = min / 60
        if(hour > 0){
            min = min % 60
            mBinding.tvTimeItem.text = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.time_formate_min_and_hour, hour, min)
        } else {
            mBinding.tvTimeItem.text = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.time_formate_min, min)
        }
        //
        mBinding.tvListensItem.text = "${info.listenNum ?: 0}"
        //
        mBinding.tvTimeAgo.text = DataTimeUtil.dateTransform1(info.modifiedAt)

        //tab
        val currentUserId = Repo.user.get()?.id ?: -1L
        mSimpleDescriptionFragment.setData(info.description)
        mMediaCommentFragment.setData(info.id, info.userId, currentUserId)
        //
        if(mBinding.viewPager.currentItem == 1){
            //当前页面是MediaCommentFragment
            mMediaCommentFragment.refreshPage()
        }
    }

    fun showShareDialog(){
        mMediaShareDialog = MediaShareDialog(this)
        mMediaShareDialog!!.setListener {
            when (it) {
                MediaShareDialog.TYPE_FACEBOOK -> {
                    shareToFacebook()
                }
                MediaShareDialog.TYPE_LINE -> {
                    shareToLine()
                }
                MediaShareDialog.TYPE_COPY_LINK -> {
                    val idStr = ConstantConfig.URL.h5SharePage(mViewModel.getCurrentContentId())
                    if (ClipboardUtil.copy(idStr)) {
                        showTopToast(true)
                        mViewModel.onShareSuccess()
                    } else {
                        showTopToast(false)
                    }
                }
            }
        }.show()
    }

    fun shareToFacebook(){
        callbackManager = CallbackManager.Factory.create();
        val shareDialog = ShareDialog(this);
        shareDialog.registerCallback(callbackManager!!, object : FacebookCallback<Sharer.Result> {
            override fun onCancel() {
                hideLoadingDialog()
                LoggerManager.i(TAG,"onCancel")
            }

            override fun onError(error: FacebookException) {
                hideLoadingDialog()
                LoggerManager.i(TAG,error.message.toString())
                error.printStackTrace()
                //
                showTopToast(false)
            }

            override fun onSuccess(result: Sharer.Result) {
                hideLoadingDialog()
                LoggerManager.i(TAG,result.toString())
                //showTopToast(true)
                mViewModel.onShareSuccess()
            }
        })
        if (ShareDialog.canShow(ShareLinkContent::class.java)) {
            showLoadingDialog()
            val linkContent: ShareLinkContent = ShareLinkContent.Builder()
                .setContentUrl(Uri.parse(ConstantConfig.URL.h5SharePage(mViewModel.getCurrentContentId())))
                .build()
            shareDialog.show(linkContent)
        }
    }

    fun shareToLine(){
        val url = ConstantConfig.URL.h5SharePage(mViewModel.getCurrentContentId())
        val LINE_PACKAGE_NAME = "jp.naver.line.android"
        try {
            val intent =  Intent()
            intent.action = Intent.ACTION_SEND
            intent.putExtra(Intent.EXTRA_TEXT, url)
            intent.type = "text/plain"
            intent.setPackage(LINE_PACKAGE_NAME)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            startActivity(intent)
            //
            mViewModel.onShareSuccess()
        } catch (e:Exception){
            e.printStackTrace()
            val openURL = Intent(Intent.ACTION_VIEW)
            openURL.data = Uri.parse("https://line.me/R/")
            startActivity(openURL)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LoggerManager.i(TAG,"onActivityResult $requestCode")
        callbackManager?.onActivityResult(requestCode, resultCode, data);
    }

    fun showTopToast(isSuccess: Boolean){
        // set data
        if (isSuccess) {
            mBinding.clTopToast.setBackgroundColor(ApplicationContext.getColor(com.sense.kukoo.common_design.R.color.fg_online))
            mBinding.tvTopToast.text = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.share_hint_succeed)
        } else {
            mBinding.clTopToast.setBackgroundColor(ApplicationContext.getColor(com.sense.kukoo.common_design.R.color.fg_error))
            mBinding.tvTopToast.text = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.share_hint_failed)
        }
        // show data
        mBinding.timerTopToast.alpha = 1F
        mBinding.timerTopToast.animate()
            .alpha(0F)
            .setDuration(2200L)
            .withStartAction { animateToShowTopToast() }
            .withEndAction { animateToHideTopToast() }
            .start()
    }

    fun animateToShowTopToast(){
        mBinding.clTopToast.animate().translationY(0F).setDuration(200L).start()
    }

    fun animateToHideTopToast(){
        mBinding.clTopToast.animate().translationY(ApplicationContext.dp2px(-114F).toFloat()).setDuration(200L).start()
    }

}